#include <iostream>
#include <fstream>


#include "httplib.h"
#include "json.hpp"

#include "devicecontrol.h"

using namespace httplib;
using namespace std;


std::string read_file(const std::string& path) {
    std::ifstream file(path);
    if (!file) return "";
    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

int main()
{
    httplib::Server svr;

    //静态页面演示
    svr.set_mount_point("/", "./static");
    svr.Get("/", [](const Request& req, Response& res) {
            std::string html = read_file("./static/index.html");
            if (html.empty()) {
                res.status = 404;
                res.set_content("File not found", "text/plain");
                return;
            }
            res.set_content(html, "text/html");
        });


    //1.上传文件演示
    //postman, body,form-data,key=file_data,类型选File,然后选择一个文件
    svr.Post("/upload", [](const httplib::Request& req, httplib::Response& res)
    {
        // 验证是否包含文件
        if (!req.has_file("file_data"))
        {
            res.status = 400;
            res.set_content("No file uploaded", "text/plain");
            return;
        }
        // 获取上传文件元数据
        const auto& file = req.get_file_value("file_data");


        std::string safe_path = "./test.gcode";

        try {
            // 写入文件
            std::ofstream ofs(safe_path, std::ios::binary);
            ofs << file.content;
            res.set_content("Upload success: " + safe_path, "text/plain");
        } catch (const std::exception& e) {
            res.status = 500;
            res.set_content("Write failed: " + std::string(e.what()), "text/plain");
        }
    });

    //2.演示路由分层，使用面向对象的时候，注意这里放的是静态函数
    svr.Get("/getstatus",DeviceControl::getStatus);

    //3.演示返回json数据包
    svr.Get("/startwork", [](const Request& req, Response& res) {

        nlohmann::json response = {
                    {"ip", "192.168.2.11"},
                    {"id", 364}
                };


        //返回纯文本
        // res.set_content("workstart!", "text/plain");

        //返回json数据包
        res.set_content(response.dump(), "application/json");
    });

    //4. 演示restful-api-http://127.0.0.1:8889/hardware?door=2 , 演示解析restful url里面的参数值demo
    svr.Get("/hardware", [](const Request& req, Response& res) {

        if (!req.has_param("door")) {
            res.status = 400;
            res.set_content("Missing 'door' parameter", "text/plain");

        }
        else
        {
            std::string door_str = req.get_param_value("door");
            try {
                int door = std::stoi(door_str);

                if (door < 1 || door > 4)
                {
                    throw std::out_of_range("Invalid door number");
                }
                // 这里执行实际的机器门设置操作...
                res.set_content("Successfully set door to " + std::to_string(door), "text/plain");

            } catch (const std::exception& e) {
                res.status = 400;
                res.set_content("Invalid door parameter: " + std::string(e.what()), "text/plain");
            }
        }

    });


    cout << "Hello World!" << endl;
    svr.listen("0.0.0.0", 8889);
    return 0;
}
